package com.tencent.wxcloudrun.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tencent.wxcloudrun.config.CustomException;
import com.tencent.wxcloudrun.pojo.bo.GetDownUrlResp;
import com.tencent.wxcloudrun.pojo.bo.GetUploadUrlResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Component
@Slf4j
public class WinXinUtils {

    @Value("${weXin.appSecret}")
    private String appSecret;

    @Value("${weXin.appId}")
    private String appId;

    @Value("${weXin.env}")
    private String env;

    /**
     * 获取AccessToken
     */
    public String getAccessToken() {
        log.info(">>>>>> 尝试获取access_token");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String body = HttpUtil.createGet(url).execute().body();
        return JSON.parseObject(body).getString("access_token");
    }

    /**
     * 获取文件上传链接
     *
     * @param fullFileName 包含路径的文件名  contract/aaa.pdf
     */
    public GetUploadUrlResp getUploadUrl(String fullFileName) {
        String accessToken = getAccessToken();
        HashMap<String, Object> req = new LinkedHashMap<>();
        req.put("env", env);
        req.put("path", fullFileName);
        String url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=" + accessToken;
        String respBody = HttpRequest.post(url).body(JSON.toJSONString(req)).execute().body();
        GetUploadUrlResp uploadUrlResp = JSON.parseObject(respBody, GetUploadUrlResp.class);
        if (0 != uploadUrlResp.getErrcode()) {
            log.error("获取文件上传链接出错  " + JSON.toJSONString(uploadUrlResp));
            throw new CustomException("获取文件上传链接出错");
        }
        return uploadUrlResp;
    }

    /**
     * 上传文件
     */
    public String uploadFile(String fullFileName, byte[] fileInfo) {
        GetUploadUrlResp uploadUrl = getUploadUrl(fullFileName);
        HttpRequest request = HttpRequest.post(uploadUrl.getUrl())
                .form("key", fullFileName).form("Signature", uploadUrl.getAuthorization())
                .form("x-cos-security-token", uploadUrl.getToken())
                .form("x-cos-meta-fileid", uploadUrl.getCos_file_id());
        request.form("file", fileInfo, fullFileName);
        HttpResponse execute = request.execute();
        return uploadUrl.getFile_id();
    }

    /**
     * 单笔的获取文件临时URL
     */
    public String batchdownloadfile(String fileId) {
        List<HashMap<String, Object>> reqPart = new ArrayList<>();
        HashMap<String, Object> reqInner = new LinkedHashMap<>();
        reqInner.put("fileid", fileId);
        reqInner.put("max_age", 3600);
        reqPart.add(reqInner);
        HashMap<String, Object> req = new LinkedHashMap<>();
        req.put("env", env);
        req.put("file_list", reqPart);
        String url = "https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=" + getAccessToken();
        String body = HttpRequest.post(url).body(JSON.toJSONString(req)).execute().body();
        GetDownUrlResp getDownUrlResp = JSONObject.parseObject(body, GetDownUrlResp.class);
        if (0 != getDownUrlResp.getErrcode()) {
            log.error("获取临时文件URL出错  " + JSON.toJSONString(getDownUrlResp));
            throw new CustomException("获取临时文件URL出错");
        }
        return getDownUrlResp.getFile_list().get(0).getDownload_url();
    }
}
